package com.tjetc.receiver;

import com.tjetc.constant.CodeConstant;
import com.tjetc.constant.MessageConstant;
import com.tjetc.constant.RedisConstant;
import com.tjetc.domain.BClassify;
import com.tjetc.domain.User;
import com.tjetc.mapper.UserMapper;
import com.tjetc.repository.UserRepository;
import com.tjetc.utils.JwtUtils;
import com.tjetc.vo.OperationMessage;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class UserReceiver {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRepository userRepository;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queues = "userQueue")
    public void processUser(OperationMessage operationMessage) {
        System.out.println("Received OperationMessage: " + operationMessage);
        HashOperations<String, Object, Object> hashOps = stringRedisTemplate.opsForHash();

        try {
            if (operationMessage.getType().equals(MessageConstant.IMPORT_ALL)) {
                List<User> list = userMapper.findAll();
                userRepository.saveAll(list);
                hashOps.put(RedisConstant.OPERATION_KEY + operationMessage.getOperationId(),
                        RedisConstant.STATE, CodeConstant.SUCCESS.toString());
                hashOps.put(RedisConstant.OPERATION_KEY + operationMessage.getOperationId(),
                        RedisConstant.DESC, "批量导入用户成功");
            } else if (operationMessage.getType().equals(MessageConstant.ADD)) {
                User user = (User) operationMessage.getData();
                userMapper.add(user);
                System.out.println("user = " + user);
                userRepository.save(user);
                hashOps.put(RedisConstant.OPERATION_KEY + operationMessage.getOperationId(),
                        RedisConstant.STATE, CodeConstant.SUCCESS.toString());
                hashOps.put(RedisConstant.OPERATION_KEY + operationMessage.getOperationId(),
                        RedisConstant.DESC, "用户注册成功");
            } else if (operationMessage.getType().equals(MessageConstant.DELETE)) {
                // 处理删除逻辑
            }
        } catch (Exception e) {
            e.printStackTrace();
            hashOps.put(RedisConstant.OPERATION_KEY + operationMessage.getOperationId(),
                    RedisConstant.STATE, CodeConstant.FAIL.toString());
            hashOps.put(RedisConstant.OPERATION_KEY + operationMessage.getOperationId(),
                    RedisConstant.DESC, "操作失败: " + e.getMessage());
        }
    }
}
